package com.example.matchingengine.service;

import com.example.matchingengine.config.TopicConfig;
import com.example.matchingengine.model.Order;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * 订单生产者服务
 * 负责将订单发送到RocketMQ消息队列，采用异步解耦架构
 */
@Slf4j
@Service
public class OrderProducerService {



    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private MeterRegistry meterRegistry;
    
    @Autowired
    private TopicConfig topicConfig;

    // 计时器 - 订单发送时间
    private Timer orderPublishTimer;
    
    // 计数器 - 发送订单数量
    private Counter orderPublishCounter;

    @PostConstruct
    public void init() {
        // 初始化监控指标
        orderPublishTimer = Timer.builder("matching.engine.order.publish")
                .description("订单发送时间")
                .register(meterRegistry);
        
        orderPublishCounter = Counter.builder("matching.engine.order.publish.count")
                .description("发送订单数量")
                .register(meterRegistry);
    }

    /**
     * 发送订单到撮合引擎
     * 采用异步方式，只发送到RocketMQ，由消费方执行撮合逻辑
     */
    public void sendOrder(Order order) {
        try {
            // 发送订单消息到RocketMQ
            String orderTopic = topicConfig.getOrderTopic(order.getSymbol());
            rocketMQTemplate.convertAndSend(orderTopic, order);
            log.info("订单已发送到RocketMQ topic {}: {}", orderTopic, order.getId());
            
            // 记录订单发送计数
            orderPublishCounter.increment();
            
        } catch (Exception e) {
            log.error("发送订单失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送订单失败", e);
        }
    }

    /**
     * 发送取消订单请求
     */
    public void sendCancelOrder(Order order) {
        try {
            // 发送取消订单消息到RocketMQ
            String cancelOrderTopic = topicConfig.getCancelOrderTopic(order.getSymbol());
            rocketMQTemplate.convertAndSend(cancelOrderTopic, order);
            log.info("取消订单请求已发送到RocketMQ topic {}: {}", cancelOrderTopic, order.getId());
            
        } catch (Exception e) {
            log.error("发送取消订单请求失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送取消订单请求失败", e);
        }
    }


}